from dashscope import Assistants, Messages, Runs, Threads

assistant = Assistants.create(
    model='qwen-max',
    name='smart helper',
    description='一个智能助手，可以通过用户诉求，调用已有的插件能力帮助用户。',
    instructions='你是一个智能助手，请记住以下信息。${document1}',  # from rag library
    tools=[
        {
            "type": "rag",
            "prompt_ra": {
                "pipeline_id": ["9c0simc8q8","13loysdy91"],  # 知识库 id ["9c0simc8q8", "13loysdy91"]
                "multiknowledge_rerank_top_n":10,  # 多个知识库总共召回的片段数
                "rerank_top_n":5, # 单个知识库召回的片段数
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query_word": {
                            "type": "str",
                            "value": "${document1}"
                        }

                    }
                }
            }

        },

    ]
)


def send_message(assistant, message='百炼是什么？'):
    print(f"Query: {message}")

    # create thread.
    # create a thread.
    thread = Threads.create()

    print(thread)

    # create a message.
    message = Messages.create(thread.id, content=message)
    # create run

    run = Runs.create(thread.id, assistant_id=assistant.id)
    print(run)

    # # get run statue
    # run_status = Runs.get(run.id, thread_id=thread.id)
    # print(run_status)

    # wait for run completed or requires_action
    run_status = Runs.wait(run.id, thread_id=thread.id)
    # print(run_status)

    # if prompt input tool result, submit tool result.

    run_status = Runs.get(run.id, thread_id=thread.id)
    print(run_status)
    # verify_status_code(run_status)

    # get the thread messages.
    msgs = Messages.list(thread.id)
    # print(msgs)
    # print(json.dumps(msgs, default=lambda o: o.__dict__, sort_keys=True, indent=4))

    print("运行结果:")
    for message in msgs['data'][::-1]:
        print("content: ", message['content'][0]['text']['value'])
    print("\n")


if __name__ == "__main__":
    send_message(assistant, message='百炼是什么?')